package com.ayic.garbagerecycle.controller;

import com.ayic.garbagerecycle.mapper.WasteMapper;
import com.ayic.garbagerecycle.pojo.*;
import com.ayic.garbagerecycle.service.StationService;
import com.ayic.garbagerecycle.service.UserService;
import com.ayic.garbagerecycle.service.WasteService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin(origins = "*", allowedHeaders = "*")
@RequestMapping("/user")
@RestController
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private WasteService wasteService;
    @Resource
    private StationService stationService;

    @GetMapping("/info/{username}")
    public Result getUserInfo(@PathVariable String username) {
        return userService.getUserInfo(username);
    }

    /**
     * 获取用户投放垃圾种类统计
     * @param username 用户ID
     * @return 垃圾种类及投放次数统计结果
     */
    @GetMapping("/recInfo/{username}")
    public Result getUserRecInfo(@PathVariable String username){
        User user = (User) userService.getUserInfo(username).getData();
        Map<String, Integer> stats = userService.getUserRecInfo(user.getUserId());
        return Result.success(stats);
    }

    // 获取用户回收记录
    @GetMapping("/wasteRec/{username}")
    public Result getUserWasteRec(@PathVariable String username){
        User user = (User) userService.getUserInfo(username).getData();
        return userService.getUserWasteRec(user.getUserId());
    }

    // 有点意义不明了
    @GetMapping("/waste/records/{username}")
    public Result getUserWasteRecords(@PathVariable String username) {
        User user = (User) userService.getUserInfo(username).getData();
        List<WasteRecord> records = wasteService.queryWasteUserRec(user.getUserId());
        return Result.success(records,"获取回收记录成功");
    }

    // 更新密码
    @PostMapping("/update-password")
    public Result updatePassword(@RequestBody User user) {
        User currentUser = (User) userService.getUserInfo(user.getUsername()).getData();
        if (currentUser != null && currentUser.getPassword().equals(user.getPassword())) {
            return userService.updatePassword(user.getUsername(), user.getTempPassword());
        }
        return Result.error("密码错误");
    }

    // 更新邮箱
    @PostMapping("/update-email")
    public Result updateEmail(@RequestBody User user) {
        User currentUser = (User) userService.getUserInfo(user.getUsername()).getData();
        if (currentUser != null && currentUser.getEmail().equals(user.getEmail())) {
            return userService.updateEmail(user.getUsername(), user.getTempEmail());
        }
        return Result.error("邮箱错误");
    }
}